<?php

namespace app\controller\admin;

use app\base\BaseEncryptController;
use app\libs\Util;
use app\model\activity\ActivityGoodsModel;
use app\model\agency\AgencyGoodsModel;
use app\model\distributor\DistributorModel;
use app\model\goods\GoodsAttributeModel;
use app\model\goods\GoodsAttributeValueModel;
use app\model\goods\GoodsCommonModel;
use app\model\goods\GoodsFreightModel;
use app\model\goods\GoodsModel;
use app\model\goods\GoodsNavbarModel;
use app\model\goods\GoodsTypeModel;
use think\Request;

/**
 * Goods 商品
 * Class Goods
 * @package app\controller
 */
class Goods extends BaseEncryptController
{
    protected function initialize()
    {
        parent::initialize();
        $this->model = new GoodsModel();
    }

    /**
     * 分页列表
     * @param string $goodsType
     * @param string $status
     * @param string $keyword
     * @param int $page
     * @param int $limit
     * @param string $activity
     * @param string $agency
     * @param string $check
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPage($goodsType = '', $status = '', $keyword = '', $page = 1, $limit = 10, $activity = '', $agency = '', $check = "")
    {
        $field = "a.*,b.name as goods_type_name";
        $goods_ids = [];
        $goods_storage = 1;
        if (!empty($activity)) {
            $activity_goods_model = new ActivityGoodsModel();
            $activity_list = $activity_goods_model->where('activity_id', $activity)->field('goods_id')->select();
            $goods_ids = [];
            foreach ($activity_list as $value) {
                $goods_ids[] = $value['goods_id'];
            }
            $goods_storage = 2;
        } else if (!empty($agency)) {
            $agency_goods_model = new AgencyGoodsModel();
            $agency_list = $agency_goods_model->where('agency_id', $agency)->field('goods_id')->select();
            $goods_ids = [];
            foreach ($agency_list as $value) {
                $goods_ids[] = $value['goods_id'];
            }
            $goods_storage = 1;
        }
        if (!empty($goods_ids)) {
            $goodsType = GoodsTypeModel::getChildId($goodsType);
            $dataList = $this->model
                ->goodsType($goodsType)
                ->keyword($keyword)
                ->whereNotIn('id', implode(',', $goods_ids))
                ->where('goods_storage', '>=', $goods_storage)
                ->order('sort', 'desc')
                ->order('id', 'desc')
                ->paginate(['page' => $page, 'list_rows' => $limit], false);
            $current = $dataList->currentPage();
            $total = $dataList->total();
            $limit = $dataList->listRows();
            $data = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $dataList->items()];
            $dataList = $data['dataList'];
        } else {
            $goodsType = GoodsTypeModel::getChildId($goodsType);
            $data = $this->model->getPageData($goodsType, $status, $keyword, $page, $limit, $field);
            $goods_ids = [];
            $freight_list = GoodsFreightModel::getFreightList();
            foreach ($data['dataList'] as &$value) {
                $goods_ids[] = $value['id'];
                $value['freight_info'] = $freight_list[$value['freight_id']];
            }
            $goods_common_model = new GoodsCommonModel();
            $item_all_list = $goods_common_model->getCommonGoodsIds($goods_ids);
            $dataList = $data['dataList'];
            foreach ($dataList as &$value) {
                if (!empty($check)) {
                    $item_list = isset($item_all_list[$value['id']]) ? $item_all_list[$value['id']] : [];
                    $ratio = floatval($value['goods_return_agency_money']) + floatval($value['goods_return_money']) + floatval($value['goods_top_money']) + floatval($value['goods_top_top_money']) + floatval($value['goods_channel_money']);
                    $value['goods_return_agency_money'] = $value['goods_return_agency_money'] * 100;
                    $value['goods_return_money'] = $value['goods_return_money'] * 100;
                    $value['goods_top_money'] = $value['goods_top_money'] * 100;
                    $value['goods_top_top_money'] = $value['goods_top_top_money'] * 100;
                    $value['goods_channel_money'] = $value['goods_channel_money'] * 100;
                    $item_show_list = [];
                    $i = 0;
                    foreach ($item_list as &$val) {
                        $val['difference_price'] = round(floatval($val['goods_sell_price']) - floatval($val['goods_cost_price']), 2);
                        $val['profits_price'] = round(floatval($val['difference_price']) * (1 - floatval($ratio)), 2);
                        if ($i < 3) {
                            $item_show_list[] = $val;
                        }
                        $i++;
                    }
                    $value['more'] = false;
                    $value['item_list_len'] = $i;
                    $value['item_show_list'] = $item_show_list;
                    $value['item_list'] = $item_list;
                }
            }
        }
        return self::returnMsg(1, [
            'totalCount' => $data['total'],
            'currentPage' => $data['current'],
            'pageList' => $dataList,
        ]);
    }

    /**
     * 单条信息
     * @param $id
     * @return \think\response\Json
     * @throws \Exception
     */
    public function getInfo($id)
    {
        $field = "a.*,b.name as goods_type_name";
        $data = $this->model->getGoodsInfo($id, $field);
        if (!empty($data)) {
            if (!empty($data['goods_parameter'])) {
                $data['goods_parameter'] = json_decode($data['goods_parameter'], true);
            } else {
                $data['goods_parameter'] = [];
            }
            $data['goods_return_agency_money'] = $data['goods_return_agency_money'] * 100;
            $data['goods_return_money'] = $data['goods_return_money'] * 100;
            $data['goods_top_money'] = $data['goods_top_money'] * 100;
            $data['goods_top_top_money'] = $data['goods_top_top_money'] * 100;
            $data['goods_channel_money'] = $data['goods_channel_money'] * 100;
            return self::returnMsg(1, $data);
        } else {
            return self::returnMsg(1001);
        }
    }

    /**
     * 保存
     * @param Request $request
     * @return \think\response\Json
     * @throws \Exception
     */
    public function onSave(Request $request)
    {
        $formData = $request->param();
        unset($formData['delete_time']);
        unset($formData['create_time']);
        unset($formData['update_time']);
        if (empty($formData['id'])) {
            $validate = 'app\validate\GoodsValidate.add';
            $formData['store_id'] = $this->currentUser['store_id'];
        } else {
            $validate = 'app\validate\GoodsValidate';
        }
        $result = $this->validate($formData, $validate);
        if (true !== $result) {
            return self::returnMsg(991, [], $result);
        } else {
            $all_money = floatval($formData['goods_return_agency_money']) + floatval($formData['goods_return_money']) + floatval($formData['goods_top_money']) + floatval($formData['goods_top_top_money']) + floatval($formData['goods_channel_money']);
            if ($all_money > 100) {
                return self::returnMsg(0, [], '佣金大于利润');
            }
            $formData['goods_return_agency_money'] = $formData['goods_return_agency_money'] / 100;
            $formData['goods_return_money'] = $formData['goods_return_money'] / 100;
            $formData['goods_top_money'] = $formData['goods_top_money'] / 100;
            $formData['goods_top_top_money'] = $formData['goods_top_top_money'] / 100;
            $formData['goods_channel_money'] = $formData['goods_channel_money'] / 100;
            $formData['goods_reserve_send'] = intval($formData['goods_reserve_send']) / 1000;
            $formData['goods_first_id'] = GoodsTypeModel::getParentId($formData['goods_type_id']);

            $ret = $this->model->addUpdateGoods($formData);
            if (false !== $ret['flag']) {
//                $id = $ret['id'];
//                $this->model->createGeneralizeImg($id);
//                $this->model->redis->hSet($this->model->redis_key, $id . "_code", 0);
                //清除无效属性
//                GoodsAttributeModel::clearGoodsAttr();
                return self::returnMsg(1);
            } else {
                return self::returnMsg(0);
            }
        }
    }

    /**
     * 删除
     * @param $id
     * @return \think\response\Json
     */
    public function onDelete($id)
    {
        $flag = $this->model::destroy(['id' => $id]);
        if (false !== $flag) {
            $this->model->delRedis($id);
            $this->model->redis->zRem($this->model->redis_key . ':rank', $id);
            $this->model->addToRecycle($id, 'GoodsModel', '商品管理', $this->currentUser['user_id'], $this->currentUser['user_type'], 'goods');
            return self::returnMsg(1);
        } else {
            return self::returnMsg(1002);
        }
    }

    /**
     * 上线状态
     * @param Request $request
     * @return \think\response\Json
     */
    public function onStatus(Request $request)
    {
        $formData = [
            'id' => $request->param('id'),
            'goods_status' => $request->param('status'),
        ];
        if (is_array($formData['id'])) {
            $list = [];
            foreach ($formData['id'] as $key => $value) {
                $list[] = ['id' => $value, 'goods_status' => $formData['goods_status']];
            }
            $ret = $this->model->saveAll($list);
            if ($ret) {
                return self::returnMsg(1);
            } else {
                return self::returnMsg(0);
            }
        } else {
            $validate = 'app\validate\GoodsValidate.upstatus';
            $result = $this->validate($formData, $validate);
            if (true !== $result) {
                return self::returnMsg(991, [], $result);
            } else {
                $ret = $this->model->saveData($formData, false, false);
                if (false !== $ret['flag']) {
                    return self::returnMsg(1);
                } else {
                    return self::returnMsg(0);
                }
            }
        }
    }

    /**
     * 热门状态
     * @param Request $request
     * @return \think\response\Json
     */
    public function onHotStatus(Request $request)
    {
        $formData = [
            'id' => $request->param('id'),
            'goods_hot_status' => $request->param('status'),
        ];
        $validate = 'app\validate\GoodsValidate.UpHotStatus';
        $result = $this->validate($formData, $validate);
        if (true !== $result) {
            return self::returnMsg(991, [], $result);
        } else {
            $ret = $this->model->saveData($formData, false, false);
            if (false !== $ret['flag']) {
                return self::returnMsg(1);
            } else {
                return self::returnMsg(0);
            }
        }
    }

    /**
     * 添加规格名称  以及规格值
     * @param Request $request
     * @return \think\response\Json
     * @throws \Exception
     */
    public function onAddAttribute(Request $request)
    {
        $formData = $request->param();
        $type = $formData['type'];
        $id = isset($formData['id']) ? $formData['id'] : '';
        if (empty($formData['name'])) {
            return self::returnMsg(0, [], '值不能为空');
        }
        $in_data = [
            'name' => $formData['name']
        ];
        $ret = false;
        switch ($type) {
            case 'attr':
                $attribute_model = new GoodsAttributeModel();
                $ret = $attribute_model->insert($in_data);
                $id = $attribute_model->getLastInsID();
                break;
            case 'value':
                $attribute_value_model = new GoodsAttributeValueModel();
                $in_data['attribute_id'] = $id;
                $ret = $attribute_value_model->insert($in_data);
                $id = $attribute_value_model->getLastInsID();
                break;
        }
        if (false !== $ret) {
            return self::returnMsg(1, $id);
        } else {
            return self::returnMsg(0);
        }
    }

    /**
     * 添加规格名称  以及规格值
     * @param Request $request
     * @return \think\response\Json
     */
    public function onDelAttribute(Request $request)
    {
        $formData = $request->param();
        $type = $formData['type'];
        $id = isset($formData['id']) ? $formData['id'] : '';
        $ret = false;
        switch ($type) {
            case 'attr':
                $attribute_model = new GoodsAttributeModel();
                $ret = $attribute_model->where(['id' => $id])->delete();
                $attribute_value_model = new GoodsAttributeValueModel();
                $ret = $attribute_value_model->where(['attribute_id' => $id])->delete();
                break;
            case 'value':
                $attribute_value_model = new GoodsAttributeValueModel();
                $ret = $attribute_value_model->where(['id' => $id])->delete();
                break;
        }
        if (false !== $ret) {
            return self::returnMsg(1);
        } else {
            return self::returnMsg(0);
        }
    }

    /**
     * 编辑、添加商品预加载数据
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function onLoadList()
    {
        $goods_type_model = new GoodsTypeModel();
        $list = $goods_type_model->select();
        $levelTree = Util::levelTreeChildren($list, 0);
        Util::listOrder($levelTree, 'sort', 'desc', 'number');
        $goods_freight_model = new GoodsFreightModel();
        $freightTemplate = $goods_freight_model->order('default DESC')->select();
        $distributor_model = new DistributorModel();
        $distributorList = $distributor_model->getAll([], "id,name");
        $goods_navbar_model = new GoodsNavbarModel();
        $levelNavTree = $goods_navbar_model->where(['status' => 0])->select();
        $levelNavTree_arr[] = [
            'id' => 0,
            'name' => "请选择",
        ];
        foreach ($levelNavTree as $value) {
            $levelNavTree_arr[] = $value;
        }
        $data = [
            'freightTemplate' => $freightTemplate,
            'levelTree' => $levelTree,
            'levelNavTree' => $levelNavTree,
            'distributorList' => $distributorList
        ];
        return self::returnMsg(1, $data);
    }

    /**
     * @param string $keyword
     * @param int $page
     * @param int $limit
     * @param string $activity_id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function onListActivity($keyword = '', $page = 1, $limit = 10, $activity_id = '')
    {
        $activity_goods_model = new ActivityGoodsModel();
        $activity_list = $activity_goods_model->where('activity_id', $activity_id)->field('attribute_ids')->select();
        $attribute_ids = [];
        foreach ($activity_list as $value) {
            $attribute_ids[] = $value['attribute_ids'];
        }
        $goods_common_model = new GoodsCommonModel();
        $dataList = $goods_common_model->getAttrIdNotInPage($attribute_ids, $keyword, $page, $limit);
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $items = $dataList->items();
        return self::returnMsg(1, [
            'totalCount' => $total,
            'currentPage' => $current,
            'pageList' => $items
        ]);
    }

    /**
     * 批量修改价格
     * @param int $type_id
     * @param int $ratio
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function onModPrice($type_id = 0, $ratio = 1)
    {
        $goodsType = GoodsTypeModel::getChildId($type_id);
        $goods_list = $this->model->alias('a')->field('id')->GoodsType($goodsType)->select();
        $goods_ids = [];
        foreach ($goods_list as $value) {
            $goods_ids[] = $value['id'];
        }
        $goods_common_model = new GoodsCommonModel();
        $goods_common_model->setCommonGoodsIdsPrice($goods_ids, $ratio);
        return self::returnMsg(1);
    }

    /**
     * 修改对应属性商品价格
     * @param $id
     * @param $price
     * @param string $type
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function onModComPrice($id = '', $price = '', $type = "cost")
    {
        $goods_common_model = new GoodsCommonModel();
        $com = $goods_common_model->where(['id' => $id])->find();
        if (empty($com)) {
            return self::returnMsg(0);
        }
        switch ($type) {
            case "cost":
                $com->goods_cost_price = $price;
                break;
            case "market":
                $com->goods_market_price = $price;
                break;
            case "sell":
                $com->goods_sell_price = $price;
                break;
            case "agency":
                $com->goods_agency_price = $price;
                break;
        }
        $ret = $com->save();
        if ($ret != false) {
            return self::returnMsg(1);
        } else {
            return self::returnMsg(0);
        }
    }

    /**
     * 修改商品单价
     * @param $id
     * @param $price
     * @return \think\response\Json
     */
    public function onModGoodsPrice($id, $price)
    {
        $goods_model = new GoodsModel();
        $ret = $goods_model->where(['id' => $id])->update(['goods_price' => $price]);
        if ($ret != false) {
            return self::returnMsg(1);
        } else {
            return self::returnMsg(0);
        }
    }
}
